﻿using System;
using System.Net.Mail;
using System.Text.RegularExpressions;

namespace WebCommon
{
    public static partial class SharedFunction
    {
        public class SmtpMailConfig
        {
            public string MailAddress { get; set; }
            public int SMTPPort { get; set; }
            public string SMTPServer { get; set; }
            public bool EnableSSL { get; set; }
            public string Password { get; set; }
        }

        public static bool SendEmail(SmtpMailConfig mailConfig, string content, string subject, Attachment[] Attachments, MailAddressCollection ToAddresses, MailAddressCollection CCAddresses, MailAddressCollection BCCAddresses, MailPriority Priority)
        {
            var mail = new MailMessage { From = new MailAddress(mailConfig.MailAddress) };
            foreach (MailAddress toAddress in ToAddresses)
                mail.To.Add(toAddress);
            if (CCAddresses != null)
                foreach (MailAddress ccAddress in CCAddresses)
                    mail.CC.Add(ccAddress);
            if (BCCAddresses != null)
                foreach (MailAddress bccAddress in BCCAddresses)
                    mail.Bcc.Add(bccAddress);
            if (Attachments != null)
                foreach (Attachment attachment in Attachments)
                    mail.Attachments.Add(attachment);
            mail.Subject = subject;
            mail.SubjectEncoding = System.Text.Encoding.UTF8;
            mail.Body = content;
            mail.BodyEncoding = System.Text.Encoding.UTF8;
            mail.IsBodyHtml = true;
            mail.Priority = Priority;
            var client = new SmtpClient
                             {
                                 Port = mailConfig.SMTPPort,
                                 Host = mailConfig.SMTPServer,
                                 EnableSsl = mailConfig.EnableSSL
                             };
            client.Credentials = new System.Net.NetworkCredential(mailConfig.MailAddress, mailConfig.Password);
            client.Send(mail);
            return true;
        }

        public static bool IsValidEmail(string email)
        {
            //regular expression pattern for valid email
            //addresses, allows for the following domains:
            //com,edu,info,gov,int,mil,net,org,biz,name,museum,coop,aero,pro,tv
            //Regular expression object
            if (!String.IsNullOrEmpty(email))
            {
                const string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                                        @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                                        @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
                var re = new Regex(strRegex);
                if (re.IsMatch(email))
                    return (true);
            }
            return (false);
        }
    }
}
